﻿using Nancy;
using Nancy.Authentication.Stateless;
using Nancy.Bootstrapper;
using Nancy.Session;
using Nancy.TinyIoc;
using RinNote.Server.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RinNote.Server.NancyBootstrapper
{
    public class Bootstrapper : DefaultNancyBootstrapper
    {
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            CookieBasedSessions.Enable(pipelines);
            var configuration = new StatelessAuthenticationConfiguration(nancyContext =>
            {
                //返回null代码token无效或用户未认证
                string token = UserAuthorization.GetToken(nancyContext);
                if (!string.IsNullOrEmpty(token))
                {
                    return UserMapper.GetUserFromAccessToken(token);
                }
                else
                {
                    return null;
                }
            });
            StatelessAuthentication.Enable(pipelines, configuration);
        }
        /// <summary>
        /// 捕获添加返回头信息。
        /// </summary>
        /// <param name="requestContainer"></param>
        /// <param name="pipelines"></param>
        /// <param name="context"></param>
        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(requestContainer, pipelines, context);
            pipelines.AfterRequest.AddItemToEndOfPipeline(c =>
            {
                c.Response.Headers["Access-Control-Allow-Origin"] = "*";//添加跨域
            });
        }
    }
}
